package com.zuihai.app.mvp.ui.widget.behavior;

import android.animation.ValueAnimator;
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;

/**
 * Created by Administrator on 2017/5/5 0005.
 */

public class AppBarBehavior extends AppBarLayout.Behavior {

    private static final int TOP_CHILD_FLING_THRESHOLD = 2;
    private boolean isPositive;
    private int mMaxDistance;
    private boolean mUp;
    private ValueAnimator mValueAnimator;

    public AppBarBehavior() {
    }

    public AppBarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mValueAnimator = ValueAnimator.ofFloat(0, 1);
    }

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
        if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
            velocityY = velocityY * -1;
        }
        if (target instanceof RecyclerView && velocityY < 0) {
            final RecyclerView recyclerView = (RecyclerView) target;
            final View firstChild = recyclerView.getChildAt(0);
            final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
//            consumed = childAdapterPosition != 0;
            if (childAdapterPosition == 0){
                child.setExpanded(true);
            }
            LogUtils.e(childAdapterPosition);
            consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
        }
//        mUp = velocityY > 0;
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, AppBarLayout abl, int layoutDirection) {
        mMaxDistance = abl.getMeasuredHeight();
        return super.onLayoutChild(parent, abl, layoutDirection);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        isPositive = dy > 0;
        if (target instanceof SwipeRefreshLayout){
            SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) target;
            LogUtils.e(refreshLayout.getChildAt(0).getTranslationY());
        }
    }
}
